/*
 * =====================================================================================
 *
 *       Filename:  dispatcherLocal.h
 *
 *    Description:  use in dispatcher thread poll
 *
 *        Version:  1.0
 *        Created:  08/01/2012 08:41:30 PM
 *       Revision:  none
 *       Compiler:  gcc/g++
 *
 *         Author:  wangtengchao , wangtengchao AT gmail.com
 *   Organization:  
 *
 * =====================================================================================
 */

#ifndef DISPATCHERLOCAL_H
#define DISPATCHERLOCAL_H

//#include "defines.h"
#include"eventHandler.h"
#include "../concurrency/mutex.h"
#include<pthread.h>
#include<map>
#include<vector>
#include<boost/shared_ptr.hpp>
namespace inm
{
    namespace net
    {

        class Demultiplexer;

        class Dispatcher
        {//Reactor class
         //thread safe  singleton
         // one thread can only have one instance
        public:
            typedef  std::map<int,EventHandlerPtr> IdEventHandlerMap;//tcp id map to eventhandler
            Dispatcher();
            ~Dispatcher();
            void setDemultplexer(Demultiplexer* dm)
            {//already pass demuplexer in constructor function,so this function is not used
                demultiplexer_ = dm;
            }
            void registerHandler(const EventHandlerPtr& eh,const short& et);
            void updateHandler(const EventHandlerPtr& eh,const short& updateType,const short& et);
            void removeHandler(const EventHandlerPtr& eh, const short& et);
            void handleEvents();
            const EventHandlerPtr& getEventHandlerByFd(int fd) const;
            void doTasks();
            void addToTasks(const Functor& f);

            void quit();
        private:
            Demultiplexer* demultiplexer_;//keep epoll or poll or dev/poll or kqueue
            IdEventHandlerMap idEventhandlerMap_;
            std::vector<Functor> tasks_;//run after poll
            inm::concurrency::MutexLock taskMutex_;//use for tasks

        };

    };
};
#endif
